package com.example.seabedmusic.views;

import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.HotSongAdapter;
import com.example.seabedmusic.entity.HotSong;
import com.example.seabedmusic.presenter.HotMusicPresenter;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HotMusicActivity extends AppCompatActivity implements HotMusicPresenter.IHotMusicView {

    @Override
    public void appendHotSongs(List<HotSong> songs) {
        int startPosition = hotSongList.size();
        hotSongList.addAll(songs);
        hotSongAdapter.notifyItemRangeInserted(startPosition, songs.size());
    }

    private HotMusicPresenter mPresenter;
    private List<HotSong> hotSongList = new ArrayList<>();
    private HotSongAdapter hotSongAdapter;

    private RecyclerView hotMusicRv;
    private ProgressBar loadingPb;
    private ImageView coverIv;
    private ImageView backIv;

    // 只保留API获取的数据控件
    private TextView updateDateTv;
    private TextView playCountTv;
    private TextView rankNameTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activityt_hot_music);

        initView();
        initData();
    }

    private void initView() {
        // 初始化控件
        hotMusicRv = findViewById(R.id.hot_music_rv);
        loadingPb = findViewById(R.id.loading_pb);
        coverIv = findViewById(R.id.hot_cover_iv);
        backIv = findViewById(R.id.back_iv);

        // 初始化API获取的数据控件
        rankNameTv = findViewById(R.id.rank_name_tv); // 排行榜名称
        updateDateTv = findViewById(R.id.update_date_tv); // 更新时间
        playCountTv = findViewById(R.id.play_count_tv); // 播放次数

        // 返回按钮
        backIv.setOnClickListener(v -> {
            finish(); // 结束当前Activity，返回上一个页面
        });

        // 初始化RecyclerView
        hotSongAdapter = new HotSongAdapter(hotSongList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        hotMusicRv.setLayoutManager(layoutManager);
        hotMusicRv.setAdapter(hotSongAdapter);

        // 设置封面点击事件
        coverIv.setOnClickListener(v -> {
            if (!hotSongList.isEmpty() && hotSongList.get(0).getCover() != null) {
                Toast.makeText(this, "查看排行榜封面", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initData() {
        mPresenter = new HotMusicPresenter(this, this);
        // 加载热门歌曲数据
        showLoading();
        mPresenter.getHot();
    }

    /* =============== 接口回调方法 =============== */

    @Override
    public void showHotSongs(List<HotSong> songs) {
        hotSongList.clear();
        hotSongList.addAll(songs);
        hotSongAdapter.notifyDataSetChanged();

        // 显示第一首歌的封面作为排行榜封面
        if (!songs.isEmpty()) {
            HotSong firstSong = songs.get(0);
            String coverUrl = firstSong.getCover();

            // 调试信息
            Log.d("HotMusic", "最终封面URL: " + coverUrl);
            Log.d("HotMusic", "是否HTTPS: " + (coverUrl != null && coverUrl.startsWith("https")));

            if (coverUrl != null && !coverUrl.isEmpty()) {
                Glide.with(this)
                        .load(coverUrl)
                        .placeholder(R.drawable.ic_music_note)
                        .error(R.drawable.ic_music_note)
                        .into(coverIv);
                coverIv.setVisibility(android.view.View.VISIBLE);
                Log.d("HotMusic", "封面加载完成: " + coverUrl);
            } else {
                Log.w("HotMusic", "封面URL为空，使用默认图片");
                coverIv.setImageResource(R.drawable.ic_music_note);
                coverIv.setVisibility(android.view.View.VISIBLE);
            }
        } else {
            Log.w("HotMusic", "歌曲列表为空，使用默认封面");
            coverIv.setImageResource(R.drawable.ic_music_note);
            coverIv.setVisibility(android.view.View.VISIBLE);
        }

        hideLoading();
    }

    // 更新排行榜信息 - 只更新API获取的数据
    @Override
    public void updateRankInfo(JSONObject rankInfo) {
        runOnUiThread(() -> {
            try {
                // 更新排行榜名称
                if (rankInfo.has("rankName") && rankNameTv != null) {
                    String rankName = rankInfo.getString("rankName");
                    rankNameTv.setText(rankName);
                }

                // 更新时间
                if (rankInfo.has("updateTime") && updateDateTv != null) {
                    updateDateTv.setText(rankInfo.getString("updateTime") + "更新");
                }

                // 播放量 - 只显示这个，因为只有这个是从API获取的
                if (rankInfo.has("playCount") && playCountTv != null) {
                    playCountTv.setText(rankInfo.getString("playCount"));
                }

                Log.d("HotMusic", "排行榜信息更新完成");

            } catch (Exception e) {
                Log.e("HotMusic", "更新排行榜信息失败: " + e.getMessage());
            }
        });
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {
        if (loadingPb != null) {
            loadingPb.setVisibility(android.view.View.VISIBLE);
        }
        if (hotMusicRv != null) {
            hotMusicRv.setVisibility(android.view.View.GONE);
        }
    }

    @Override
    public void hideLoading() {
        if (loadingPb != null) {
            loadingPb.setVisibility(android.view.View.GONE);
        }
        if (hotMusicRv != null) {
            hotMusicRv.setVisibility(android.view.View.VISIBLE);
        }
    }

    /**
     * 获取当前的热歌列表（供适配器使用）
     */
    public List<HotSong> getHotSongList() {
        return hotSongList;
    }
}